package com.imy.alscript;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.imy.virtual.GmsSupport;
import com.imy.virtual.client.core.InstallStrategy;
import com.imy.virtual.client.core.VirtualCore;
import com.imy.virtual.client.stub.VASettings;
import com.imy.virtual.helper.utils.AppUtils;
import com.imy.virtual.helper.utils.ModeUtils;
import com.imy.virtual.remote.InstallResult;
import com.imy.virtual.remote.InstalledAppInfo;
import com.imy.alscript.models.AppInfo;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class AppListActivity extends AppCompatActivity {
  private ListView mListView;
  public static final String EXTRA_APP_INFO_LIST = "va.extra.APP_INFO_LIST";
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_app_list);
    mListView = (ListView) findViewById(R.id.list_view);
    //获取数据
    Thread thread = new Thread(new Runnable() {
      @Override
      public void run() {
        getApp(getBaseContext());
      }
    });
    thread.start();
  }

  private void getApp(Context context) {
    List<PackageInfo> installedPackages = context.getPackageManager().getInstalledPackages(0);
    Log.i("AppListActivity","installedPackages:"+installedPackages.size());
    List<AppInfo> appInfos = convertPackageInfoToAppData(context, installedPackages, true);
    setAdapter(appInfos);
  }

  private void setAdapter(final List<AppInfo> appInfos) {
    runOnUiThread(new Runnable() {
      @Override
      public void run() {
        ListAdapter listAdapter = new ListAdapter(AppListActivity.this, appInfos);
        mListView.setAdapter(listAdapter);
        listAdapter.setOnItemClickListener(new BaseSimpleListAdapter.onItemClickListener<AppInfo>() {
          @Override
          public void onItemClick(AppInfo info, View itemView, int position) {
            //
            InstallResult installResult = VirtualCore.get().installPackage(info.path, InstallStrategy.UPDATE_IF_EXIST);
            if (installResult.isSuccess){
              Toast.makeText(getBaseContext(),"安装成功",Toast.LENGTH_LONG).show();
              try {
                VirtualCore.get().preOpt(info.packageName);
              } catch (IOException e) {
                e.printStackTrace();
              }
            }else {
              Toast.makeText(getBaseContext(),"安装失败:"+installResult.error,Toast.LENGTH_LONG).show();
              if (installResult.code==InstallResult.ONLY_SUPPORT_64BIT){
                //检查是否安装了app
                boolean b = AppUtils.check64SupportInstall(AppListActivity.this);
                if (b){
                  Log.i("KBAPKListActivity","已安装64支持");
                  //启动64支持器
                  start64Support(info);
                }else {
                  Log.i("KBAPKListActivity","未已安装64支持");
                  Toast.makeText(AppListActivity.this,installResult.error,Toast.LENGTH_LONG).show();
                }
              }
            }
          }
        });
      }
    });
  }

  private void start64Support(AppInfo info) {
    try {
      Intent intent=new Intent(Intent.ACTION_VIEW, Uri.parse("kykbsupport://open"));
      intent.putExtra(VASettings.APK_PATH,info.path);
      intent.putExtra(VASettings.APK_PACKAGE,info.packageName);
      intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      startActivity(intent);
    }catch (Exception e){
      Log.i("KBAPKListActivity","e:"+e.getMessage());
      Toast.makeText(this,"启动64支持器失败，请确认是否安装了",Toast.LENGTH_LONG).show();
    }
  }

  private List<AppInfo> convertPackageInfoToAppData(Context context, List<PackageInfo> pkgList, boolean fastOpen) {
    PackageManager pm = context.getPackageManager();
    List<AppInfo> list = new ArrayList<>(pkgList.size());
    String hostPkg = VirtualCore.get().getHostPkg();
    for (PackageInfo pkg : pkgList) {
      // ignore the host package
      if (hostPkg.equals(pkg.packageName)) {
        continue;
      }
      // ignore the System package
      if (isSystemApplication(pkg)) {
        continue;
      }
      ApplicationInfo ai = pkg.applicationInfo;
      String path = ai.publicSourceDir != null ? ai.publicSourceDir : ai.sourceDir;
      if (path == null) {
        continue;
      }
      //得到路径 通过
      boolean mode = ModeUtils.isMode(path);
      AppInfo info = new AppInfo();
      info.packageName = pkg.packageName;
      info.fastOpen = fastOpen;
      info.path = path;
      info.icon = ai.loadIcon(pm);
      info.name = ai.loadLabel(pm);
      info.isMode =mode;
      InstalledAppInfo installedAppInfo = VirtualCore.get().getInstalledAppInfo(pkg.packageName, 0);
      if (installedAppInfo != null) {
        info.cloneCount = installedAppInfo.getInstalledUsers().length;
      }
      list.add(info);
    }
    return list;
  }

  private boolean isSystemApplication(PackageInfo packageInfo) {
    return (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0
        && !GmsSupport.isGmsFamilyPackage(packageInfo.packageName);
  }

}